<template>
  <div>
    <a-spin :spinning="loading" tip="正在初始化考试，请稍候...">
      <div style="margin:0 5px">
        <a-card style="background-color: #0a9fe5;width: 100%">
          <a-flex justify="space-between">
            <div>
              <a-flex>
                <a-flex align="center">
                  <div>
                    <a-avatar :size="55" :src="getFileAccessHttpUrl(userInfo.avatar)" />
                  </div>
                  <div style="margin-left: 15px">
                    <div style="color:#FFF;">{{ userInfo.realname }}</div>
                    <div style="color:#FFF;">{{ userInfo.username }}</div>
                  </div>
                </a-flex>
                <div style="margin-left: 100px">
                  <div class="examTitle">{{ form.examTitle }}</div>
                  <div class="examInfo">
                    本试卷共{{ form.questionCount }}题，满分{{ form.totalScore
                    }}分。考试用时{{ form.totalTime }}分钟。
                  </div>

                </div>
              </a-flex>
            </div>
            <a-flex align="flex-end">
              <div>
                <div style="color: white">剩余时间：</div>
                <div class="countDownClass">
                  <countdown :time="remainTime" format="HH:mm:ss" v-if="remainTime"
                             @finish="doHandler()">
                    <template #="{ resolved }">
                      <span class="countdown-item">{{ resolved.HH }}</span><span
                      class="timeColon">:</span>
                      <span class="countdown-item">{{ resolved.mm }}</span><span
                      class="timeColon">:</span>
                      <span class="countdown-item">{{ resolved.ss }}</span>
                    </template>
                  </countdown>
                </div>
              </div>
              <div style="margin-left: 50px">
                <a-button type="primary" danger @click="commitExam">
                  提交试卷
                </a-button>
              </div>
            </a-flex>
          </a-flex>
        </a-card>
      </div>
      <div class="all-box">
        <div class="all-box-left">
          <div class="a-card is-always-shadow left-box left-box-normal" style="width: calc(20vw)">
            <a-card>
              <div class="answerCard">
                <svg class="icon-third" aria-hidden="true" style="font-size: 6px">
                  <use xlink:href="#icon-third-Ajia-"></use>
                </svg>
                <span style="font-size: 16px;margin-left: 5px">答题卡</span>
              </div>
              <div class="group-card" v-for="(item,index) in form.answerCardList" :key="index">
                <template v-for="(mapItem,key) in item" :key="key">
                  <span class="typeClass">{{ key }}</span>
                  <a-divider />
                  <div class="group-card-body">
                    共 <span class="numberClass">{{ mapItem.questionCount }}</span> 题，共 <span
                    class="numberClass">{{ mapItem.questionScore }}</span> 分
                  </div>
                  <div class="card-box">
                    <div class="item" v-for="(numItem,index1) in mapItem.indexList" :key="index1"
                         @click="selectQuestion(numItem)">
                      <div :class="cardItemClass(numItem,mapItem.questionType)">{{ numItem }}</div>
                    </div>
                  </div>
                </template>
              </div>
              <a-row style="position:fixed;bottom:10px;font-size: 13px" :gutter="8">
                <a-divider style="margin-bottom: 5px" />
                <a-col :span="4">
                  <div class="tip">
                    <div class="info"></div>
                  </div>
                </a-col>
                <a-col :span="4" style="line-height: 28px">
                  未答
                </a-col>
                <a-col :span="4">
                  <div class="tip">
                    <div class="success"></div>
                  </div>
                </a-col>
                <a-col :span="4" style="line-height: 28px">
                  已答
                </a-col>
                <a-col :span="4">
                  <div class="tip">
                    <div class="warning"></div>
                  </div>
                </a-col>
                <a-col :span="4" style="line-height: 28px">
                  当前
                </a-col>
              </a-row>
            </a-card>
          </div>
        </div>
        <div class="all-box-center">
          <div class="a-card content-card is-always-shadow"
               style="width: calc(56.5vw);height: calc(100vh - 115px);position: fixed;overflow: auto">
            <a-card>
              <div class="list-box">
                <div class="list-qu" style="width: 100%">
                  <a-alert style="padding-left: 10px" :message="message" type="info" show-icon />
                  <div class="qu-box">
                    <div class="qu-item">
                      <div class="num">
                        {{ cardItem.questionIndex }}
                      </div>
                      <div class="content">
                        <div v-html="cardItem.question.content"></div>
                      </div>
                    </div>
                    <div v-if="cardItem.questionType == 4">
                      <Tinymce v-model="cardItem.subjectiveAnswer" @blur="cacheSubjectiveAnswer"
                               :height="250" />
                    </div>
                    <div class="qu-answer" v-else-if="cardItem.questionType == 5">
                      <div class="item" v-for="(answerItem,index2) in cardItem.question.answerList"
                           :key="index2">
                        <div class="tag">{{ answerItem.tag }}</div>
                        <div class="content">
                          <a-input v-model:value="answerItem.content" @blur="cacheBlankAnswer()" />

                        </div>
                      </div>
                    </div>
                    <div class="qu-answer"
                         v-else-if="cardItem.questionType == 1 || cardItem.questionType == 2 || cardItem.questionType == 3">
                      <div :class="answerItemClass(index2)"
                           v-for="(answerItem,index2) in cardItem.question.answerList"
                           :key="index2"
                           @click="selectAnswer(index2,cardItem.questionType,answerItem.id)">
                        <div class="tag">{{ answerItem.tag }}

                        </div>
                        <div class="content">
                          {{ answerItem.content }}
                          <img
                            :src="getFileAccessHttpUrl(answerItem.contentImage)"
                            :title="answerItem.contentImage"
                            style="width: 150px; height: 100px; object-fit: cover;"
                          />
                        </div>
                      </div>
                    </div>
                    <!--组合题-->
                    <div class="qu-answer" v-else-if="cardItem.questionType == 6">
                      <div class="combinaClass">
                        本大题共{{ cardItem?.subQuestionList?.length || 0 }}小题
                      </div>
                      <div v-for="(subQuestion,subQuestionIndex) in cardItem.subQuestionList"
                           :key="subQuestionIndex">
                        <a-card>
                          <div class="qu-item">
                            <div>
                              （{{ subQuestion.questionIndex }}）<span
                              style="color: #448efc;">【{{ subQuestion.questionTypeName }}】</span>
                            </div>
                            <div class="content flex">
                              <div v-html="subQuestion.question.content"></div>
                              <div class="scoreStyle">({{ subQuestion.questionScore }}分)</div>
                            </div>
                          </div>
                          <div v-if="subQuestion.questionType == 4">
                            <Tinymce v-model="subQuestion.subjectiveAnswer"
                                     @blur="cacheSubSimpleAnswer(subQuestion)"
                                     :height="250" />
                          </div>
                          <div class="qu-answer" v-else-if="subQuestion.questionType == 5">
                            <div class="item"
                                 v-for="(subQuestionAnswer,subQuestionAnswerIndex) in subQuestion.question.answerList"
                                 :key="subQuestionAnswerIndex">
                              <div class="tag">{{ subQuestionAnswer.tag }}</div>
                              <div class="content">
                                <a-input v-model:value="subQuestionAnswer.content"
                                         @blur="cacheSubBlankAnswer(subQuestion)" />
                              </div>
                            </div>
                          </div>
                          <div class="qu-answer"
                               v-else-if="subQuestion.questionType == 1 || subQuestion.questionType == 2 || subQuestion.questionType == 3">
                            <div
                              :class="answerSubQuestionClass(subQuestionAnswerIndex,subQuestion.questionIndex)"
                              v-for="(subQuestionAnswer,subQuestionAnswerIndex) in subQuestion.question.answerList"
                              :key="subQuestionAnswerIndex"
                              @click="selectSubQuestionAnswer(subQuestionAnswerIndex,subQuestion.questionType,
                             subQuestionAnswer.id,subQuestion.questionIndex)">
                              <div class="tag">{{ subQuestionAnswer.tag }}</div>
                              <div class="content">
                                {{ subQuestionAnswer.content }}
                              </div>
                            </div>
                          </div>
                        </a-card>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <div style="margin-top: 20px">
                <a-button type="primary" v-if="cardItem.questionIndex != 1"
                          style="width: 100px;margin-right: 30px"
                          :icon="h(LeftOutlined)"
                          @click="handPrevious()">上一题
                </a-button>
                <a-button type="primary" danger
                          v-if="cardItem.questionIndex != form.userExamQuestionList.length"
                          :icon="h(RightOutlined)" @click="handNext()"
                          style="width: 100px;">下一题
                </a-button>
              </div>
            </a-card>
          </div>
        </div>
        <div class="all-box-right">
          <div class="a-card is-always-shadow"
               style="width: calc(20vw);height: calc(100vh - 115px);">
            <a-card>
              <DynamicClock /> <!--echarts实现的动态时钟-->
              <div class="processClass">
                <p>当前答题进度：</p>
                <a-progress :steps="10" :percent="process" :size="20" />
              </div>
              <Snap v-if="form.snapOn"
                    :snapIntervalTime="form.snapIntervalTime" :userExamId="userExamId" />
            </a-card>
          </div>
        </div>
      </div>
	  <div  :class=" [alertActive ? 'float-notice active' : 'float-notice']"  v-if="form.countdownEnable">
		  <p>请注意考试时间还剩<span style="color:red">{{remainingTime}}</span>分钟<br>请考生抓紧时间答题</p>
	  </div>
    </a-spin>
  </div>
</template>

<script lang="ts" setup>
import { createVNode, h, onBeforeUnmount, onMounted, ref, watch } from "vue";
import { apiCacheExamAnswer, apiExamDetail, apiGetCacheAnswer, apiSubmitExam } from "@/api/exam";
import { useMessage } from "@/hooks/web/useMessage";
import { Modal } from "ant-design-vue";
import { ExclamationCircleOutlined, LeftOutlined, RightOutlined } from "@ant-design/icons-vue";
import { useRoute, useRouter } from "vue-router";
import { useLeaveStore } from "@/store/modules/leaveExam";
import { Tinymce } from "@/components/public/Tinymce";
import DynamicClock from "@/components/exam/DynamicClock.vue";
import { useWebStore } from "@/store";
import { getFileAccessHttpUrl } from "@/utils/compUtils";
import Countdown from "vue3-countdown";
import Snap from "@/components/snap/Snap.vue";

const loading = ref<boolean>(false);
const webStore = useWebStore();
const userInfo = ref<any>({});

const route = useRoute();
const userExamId = route.params?.id ?? -1;
const router = useRouter();
const { createConfirm } = useMessage();
const form: any = ref<any>({
  userExamQuestionList: []
});
const cardItem: any = ref<any>({
  question: {
    answerList: []
  },
  subjectiveAnswer: "",
  subQuestionList: []
});
//试题信息
const message = ref<any>();
const leaveStore = useLeaveStore();
const alertBoxList = ref([]);
const alertActive = ref<boolean>(false);
const remainingTime = ref<number>(0);
//当前题的答案索引
const currentAnswerIndex = ref<any>([]);
//考试剩余时间
const remainTime = ref<number>();
const confirmTitle = ref<any>();
//所有试题的答案
const questionAnswers = ref<any>([]);
//本题答案
const answers = ref<any>([]);

//是否进行切屏检测
const leaveOn = ref<boolean>(false);
//可以切屏的次数
const totalLeaveTimes = ref<any>();
//切换到其他页面多长时间判定为切屏
const leaveTime = ref<any>();
//切屏提示消息
const switchMsg = ref<any>();

onMounted(() => {
  //初始化试题和答题卡
  initFormData();
  userInfo.value = webStore.getUserInfo;
});

/**
 * 生成组合题子试题序号
 * @param subQuestion
 */
function generateSubQuestionIndex(subQuestionIndex) {
  let parentIndex = cardItem.value.questionIndex;
  return parentIndex + "." + subQuestionIndex;
}


//缓存当前主观题的答案
function cacheSubjectiveAnswer() {
  cacheSubjective(cardItem.value, cardItem.value.questionIndex);
}

//组合题缓存简答题答案
function cacheSubSimpleAnswer(subQuestion) {
  let subIndex = generateSubQuestionIndex(subQuestion.questionIndex);
  cacheSubjective(subQuestion, subIndex);
}

function cacheSubjective(questionItem, questionIndex) {
  //先删除
  questionAnswers.value.forEach((item, index1) => {
    if (item.index == questionIndex) {
      questionAnswers.value.splice(index1, 1);
    }
  });
  if (!!questionItem?.subjectiveAnswer) {
    questionAnswers.value.push({
      index: questionIndex,
      questionType: questionItem.questionType,
      subjectiveAnswer: questionItem.subjectiveAnswer
    });
    cacheAnswer();
  }
}

//缓存填空题答案
function cacheBlankAnswer() {
  cacheBlank(cardItem.value, cardItem.value.questionIndex);
}

//组合体填空题缓存答案
function cacheSubBlankAnswer(subQuestion) {
  let subIndex = generateSubQuestionIndex(subQuestion.questionIndex);
  cacheBlank(subQuestion, subIndex);
}

function cacheBlank(questionItem, questionIndex) {
  if (checkBlankIsAnswered(questionItem)) { //作答了，则替换原来的值（存在的话）
    console.log("回答了，则替换原来的值");
    //先删除
    questionAnswers.value.forEach((item, index1) => {
      if (item.index == questionIndex) {
        questionAnswers.value.splice(index1, 1);
      }
    });
    let arr: any = [];
    questionItem.question.answerList.forEach((item: any) => {
      if (item.content && item.content.length > 0 && item.content.trim().length > 0) {
        arr.push({ tag: item.tag, content: item.content.trim() });
      }
    });
    questionAnswers.value.push({
      index: questionIndex,
      questionType: questionItem.questionType,
      blankAnswer: JSON.stringify(arr)
    });
  } else { //不作答，删掉原来的答案
    console.log("不作答，删掉原来的答案");
    questionAnswers.value.forEach((item: any, index1: any) => {
      if (item.index == questionIndex) {
        questionAnswers.value.splice(index1, 1);
      }
    });
  }
  console.log(questionAnswers.value);
  cacheAnswer();
}


//检查当前填空题是否已经回答
function checkBlankIsAnswered(questionItem) {
  if (questionItem.questionType == 5) {
    for (let item of questionItem.question.answerList) {
      if (item.content && item.content.length > 0 && item.content.trim().length > 0) {
        return true;
      }
    }
    return false;
  }
}

//确认对话框
function showConfirm() {
  Modal.confirm({
    title: "提示",
    icon: createVNode(ExclamationCircleOutlined),
    content: confirmTitle.value,
    onOk() {
      submit();
    },
    onCancel() {
    }
  });
}

//初始化试题和选项卡
async function initFormData() {
  loading.value = true;

  //清空当前题索引
  currentAnswerIndex.value = [];
  //初始化清空已选答案
  questionAnswers.value = [];

  try {
    const data: any = await apiExamDetail(userExamId);
    form.value = { ...data.result };
    if (data.result.limitTime) {
      let nowTime = new Date();
      let endTime = new Date(data.result.limitTime);
      remainTime.value = endTime.getTime() - nowTime.getTime();
	  if(data.result.countdownEnable){
		  alertBoxList.value = data.result.countdown.split(",").map(Number).sort((a, b) => b - a)
		  countdownTime(endTime)
	  }
    }

    leaveOn.value = data.result.leaveOn;
    totalLeaveTimes.value = data.result.totalLeaveTimes;
    leaveTime.value = data.result.leaveTime;

    //获取缓存的答案
    let cacheAnswer: any = await apiGetCacheAnswer(userExamId);

    // 获得第一题内容
    getQuestion(1);

    //根据缓存的答案，初始化
    initByCacheAnswer(cacheAnswer.result);

    // 在页面加载时读取sessionStorage里的状态信息
    let leaveTimes: any = sessionStorage.getItem("leave-times");
    if (leaveTimes && leaveTimes > 0) {
      leaveStore.setLeaveTimes(leaveTimes);
      sessionStorage.removeItem("leave-times");
    }
    //监听浏览器刷新和关闭事件
    window.addEventListener("beforeunload", e => handleBeforeUnload(e));
  } finally {
    loading.value = false;
  }
}

function countdownTime(endTime){
	console.log("alertBoxList:",alertBoxList.value)
	let realEndTime = endTime;
	if(alertBoxList.value.length > 0){
		remainingTime.value = alertBoxList.value[0]
		let alertTime =  endTime.setMinutes(endTime.getMinutes() - alertBoxList.value[0])
		realEndTime = new Date(endTime).setMinutes(new Date(endTime).getMinutes() + alertBoxList.value[0]);
		console.log("realEndTime:",realEndTime)
	let intervalAlert = setInterval(function(){
		console.log("new Date(alertTime):",new Date(alertTime))
		let nowTime = new Date();
		if(nowTime >= new Date(alertTime)){
			alertActive.value = true;
			alertBoxList.value.splice(0, 1);
			clearInterval(intervalAlert);
			setTimeout(function(){
				alertActive.value = false;
				if(alertBoxList.value.length > 0){
					countdownTime(new Date(realEndTime))
				}
			},10000)
		}
	},1000)
	}
}



//根据缓存的答案，初始化
function initByCacheAnswer(cacheAnswer) {
  if (cacheAnswer && cacheAnswer.examAnswers.length > 0) {
    //取试题的答案
    questionAnswers.value = cacheAnswer.examAnswers;
    //取出第一题
    fillAnswer(1);
  }
}

//获取当前试题
function getQuestion(index) {
  if (form.value.userExamQuestionList && form.value.userExamQuestionList.length > 0) {
    const list = form.value.userExamQuestionList.filter((val: any) => val.questionIndex == index);
    if (list && list.length > 0) {
      cardItem.value = list[0];
    }
    if (cardItem.value.questionType == 4) {
      cardItem.value.subjectiveAnswer = cardItem.value?.subjectiveAnswer ?? "";
    }
    message.value = cardItem.value.questionTypeName + "（本题" + cardItem.value.questionScore + "分）";
  }
}

// 答题卡样式
function cardItemClass(index, questionType) {
  if (index == cardItem.value.questionIndex) {
    return "num warning";
  } else {
    if (questionType != 6) {
      const tmpList = questionAnswers.value.filter(val => val.index == index);
      if (tmpList && tmpList.length > 0) {
        return "num success"; // 已经回答
      } else {
        return "num info";
      }
    } else {
      const questionAnswerList: any = questionAnswers.value.filter(val => val.index.toString().startsWith(index + "."));
      if (questionAnswerList?.length > 0) {
        return "num success"; // 已经回答
      } else {
        return "num info";
      }
    }
  }
}

function answerItemClass(index) {
  let answerIndex = currentAnswerIndex.value.filter(val => val == index);
  if (answerIndex && answerIndex.length > 0) {
    return "item active";
  } else {
    return "item";
  }
}

//组合题样式（单选 多选 判断）
function answerSubQuestionClass(index, subQuestionIndex) {
  let subIndex = generateSubQuestionIndex(subQuestionIndex);
  const answer = currentAnswerIndex.value.filter(val => val.index == subIndex)[0];
  if (answer) {
    const answerIndex = answer.answerIndex.filter(val => val == index);
    if (answerIndex && answerIndex.length > 0) {
      return "item active";
    } else {
      return "item";
    }
  } else {
    return "item";
  }
}

//选择试题
function selectQuestion(numItem) {
  currentAnswerIndex.value = [];
  answers.value = [];
  getQuestion(numItem);
  fillAnswer(numItem);
  cacheAnswer();
}

/**
 * 下一题
 */
function handNext() {
  currentAnswerIndex.value = [];
  answers.value = [];
  const index = cardItem.value.questionIndex + 1;
  getQuestion(index);
  fillAnswer(index);
  cacheAnswer();
}

/**
 * 上一题
 */
function handPrevious() {
  currentAnswerIndex.value = [];
  answers.value = [];
  const index = cardItem.value.questionIndex - 1;
  getQuestion(index);
  fillAnswer(index);
  cacheAnswer();
}

//缓存答案到redis
function cacheAnswer() {
  let params = {
    limitTime: form.value.limitTime,
    userExamId: userExamId,
    examAnswers: questionAnswers.value
  };
  apiCacheExamAnswer(params);
}


//填充答案
function fillAnswer(index) {
  const questionItem: any = form.value.userExamQuestionList.filter((val: any) => val.questionIndex == index)[0];
  if (questionItem.questionType != 6) {
    const questionAnswer: any = questionAnswers.value.filter(val => val.index == index)[0];
    if (questionAnswer) {
      //单选，多选，判断才去勾选答案样式
      if (questionItem.questionType == 1 || questionItem.questionType == 2 || questionItem.questionType == 3) {
        currentAnswerIndex.value = questionAnswer.answerIndex;
        answers.value = questionAnswer.answers;
      } else if (questionItem.questionType == 4) {//简答题回填答案到富文本框
        questionItem.subjectiveAnswer = questionAnswer?.subjectiveAnswer ?? "";
      } else if (questionItem.questionType == 5) {//填空题回填答案到输入框
        fillBlank(questionAnswer, cardItem.value);
      }
    }
  } else {//组合题
    let subIndex = questionItem.questionIndex + ".";
    const questionAnswerList: any = questionAnswers.value.filter(val => val.index.toString().startsWith(subIndex));
    if (questionAnswerList?.length > 0) {
      questionAnswerList.forEach((item: any) => {
        if (item.questionType == 1 || item.questionType == 2 || item.questionType == 3) {
          let caiObj: any = {
            index: item.index,
            answerIndex: item.answerIndex.slice()
          };
          currentAnswerIndex.value.push(caiObj);
          let ansObj: any = {
            index: item.index,
            answerId: item.answers.slice()
          };
          answers.value.push(ansObj);
        } else if (item.questionType == 4) {
          const question = cardItem.value.subQuestionList.filter((subQuestion: any) => (subIndex + subQuestion.questionIndex) == item.index)[0];
          question.subjectiveAnswer = item?.subjectiveAnswer ?? "";
        } else if (item.questionType == 5) {
          const question = cardItem.value.subQuestionList.filter((subQuestion: any) => (subIndex + subQuestion.questionIndex) == item.index)[0];
          fillBlank(item, question);
        }
      });
    }
  }
}

//回填填空题答案
function fillBlank(questionAnswer, questionItem) {
  let answer = questionAnswer.blankAnswer;
  let blankAnswerArr = JSON.parse(answer);
  questionItem.question.answerList.forEach((item: any) => {
    const answerList = blankAnswerArr.filter((val: any) => val.tag == item.tag);
    if (answerList && answerList.length > 0) {
      item.content = answerList[0].content;
    }
  });
}

/************************组合题选择答案************************/
function selectSubQuestionAnswer(index, questionType, answerId, subQuestionIndex) {
  let subIndex = generateSubQuestionIndex(subQuestionIndex);
  const subQuestion = questionAnswers.value.filter((val: any) => val.index == subIndex)[0];
  if (subQuestion) {
    const answer = subQuestion.answers.filter((val: any) => val == answerId)[0];
    if (answer) {
      //如果是已经勾选的答案，则删除-------取消
      subQuestionCanceled(subQuestion, index, questionType, answerId, subIndex);
    } else {
      //选择答案
      subQuestionSelected(index, questionType, answerId, subIndex);
    }
  } else {
    //选择答案
    subQuestionSelected(index, questionType, answerId, subIndex);
  }
}

// 选择答案
function subQuestionSelected(index, questionType, answerId, subIndex) {
  console.log("选择答案");
  //-------选择答案
  if (questionType == 1 || questionType == 3) {
    if (currentAnswerIndex.value.length > 0) {
      currentAnswerIndex.value.forEach((item: any, cuIndex) => {
        if (item.index == subIndex) {
          currentAnswerIndex.value.splice(cuIndex, 1);
        }
      });
    }
    if (answers.value.length > 0) {
      answers.value.forEach((item: any, awIndex) => {
        if (item.index == subIndex) {
          answers.value.splice(awIndex, 1);
        }
      });
    }
  }
  const cai = currentAnswerIndex.value.filter(val => val.index == subIndex)[0];
  if (!cai) {
    let caiObj: any = {
      index: subIndex,
      answerIndex: []
    };
    caiObj.answerIndex.push(index);
    currentAnswerIndex.value.push(caiObj);
  } else {
    cai.answerIndex.push(index);
  }
  const ans = answers.value.filter(val => val.index == subIndex)[0];
  if (!ans) {
    let ansObj: any = {
      index: subIndex,
      answerId: []
    };
    ansObj.answerId.push(answerId);
    answers.value.push(ansObj);
  } else {
    ans.answerId.push(answerId);
  }

  //先删除对应试题的答案
  questionAnswers.value.forEach((item, index1) => {
    if (item.index == subIndex) {
      questionAnswers.value.splice(index1, 1);
    }
  });
  const ansTmp = answers.value.filter(val => val.index == subIndex)[0];
  const caiTmp = currentAnswerIndex.value.filter(val => val.index == subIndex)[0];

  questionAnswers.value.push({
    index: subIndex,
    questionType: questionType,
    answers: ansTmp.answerId.slice(), //复制数组
    answerIndex: caiTmp.answerIndex.slice()
  });
  console.log(questionAnswers.value);
}

//取消答案
function subQuestionCanceled(questionAnswer, index, questionType, answerId, subIndex) {
  console.log("取消答案");
  currentAnswerIndex.value.forEach((item: any) => {
    if (item.index == subIndex) {
      item.answerIndex = item.answerIndex.filter(val => val != index);
    }
  });
  answers.value.forEach((item: any) => {
    if (item.index == subIndex) {
      item.answerId = item.answerId.filter(val => val != answerId);
    }
  });
  //删除勾选样式
  const caiTmp = currentAnswerIndex.value.filter(val => val.index == subIndex)[0];
  const ansTmp = answers.value.filter(val => val.index == subIndex)[0];
  questionAnswer.answerIndex = caiTmp.answerIndex.slice();
  questionAnswer.answers = ansTmp.answerId.slice();
  if (questionAnswer.answers.length == 0) {//如果没有答案则清除index
    questionAnswers.value = questionAnswers.value.filter(val => val.index != subIndex);
  }
  console.log(questionAnswers.value);
}

/****************************非组合题（单选，多选，判断）**********************************/
//选择或者取消答案
function selectAnswer(index, questionType, answerId) {
  const questionAnswer = questionAnswers.value.filter(val => val.index == cardItem.value.questionIndex)[0];
  if (questionAnswer) {
    if (questionAnswer.answers && questionAnswer.answers.length > 0) {
      const answer = questionAnswer.answers.filter((val: any) => val == answerId)[0];
      if (answer) {
        //如果是已经勾选的答案，则删除-------取消
        canceled(questionAnswer, index, questionType, answerId);
      } else {
        //选择答案
        selected(index, questionType, answerId);
      }
    }
  } else {
    //选择答案
    selected(index, questionType, answerId);
  }
}


//取消答案
function canceled(questionAnswer, index, questionType, answerId) {
  console.log("取消答案");
  //删除勾选样式
  currentAnswerIndex.value = currentAnswerIndex.value.filter(val => val != index);
  questionAnswer.answerIndex = currentAnswerIndex.value.slice();

  //删除答案
  answers.value = answers.value.filter(val => val != answerId);
  questionAnswer.answers = answers.value.slice();
  if (questionAnswer.answers.length == 0) {//如果没有答案则清除index
    questionAnswers.value = questionAnswers.value.filter(val => val.index != cardItem.value.questionIndex);
  }
  console.log(questionAnswers.value);
}


// 选择答案
function selected(index, questionType, answerId) {
  console.log("选择答案");
  //-------选择答案
  if (questionType == 1 || questionType == 3) {
    currentAnswerIndex.value = [];
    answers.value = [];
  }
  currentAnswerIndex.value.push(index);
  answers.value.push(answerId);

  //先删除对应试题的答案
  questionAnswers.value.forEach((item, index1) => {
    if (item.index == cardItem.value.questionIndex) {
      questionAnswers.value.splice(index1, 1);
    }
  });
  questionAnswers.value.push({
    index: cardItem.value.questionIndex,
    questionType: questionType,
    answers: answers.value.slice(), //复制数组
    answerIndex: currentAnswerIndex.value.slice()
  });
  console.log(questionAnswers.value);
}

/**
 * 有多少题没答的
 */
function listNotAnswered() {
  let noAnswered: any = [];
  form.value.userExamQuestionList.forEach((item: any) => {
    if (item.questionType == 6) {
      const answeredList = questionAnswers.value.filter((val: any) => val.index.toString().startsWith(item.questionIndex + "."));
      if (!answeredList || answeredList.length == 0) {
        noAnswered.push(item.index);
      }
    } else {
      const answeredList = questionAnswers.value.filter((val: any) => val.index == item.questionIndex);
      if (!answeredList || answeredList.length == 0) {
        noAnswered.push(item.index);
      }
    }
  });
  return noAnswered;
}

//交卷
function commitExam() {
  let noAnswered = listNotAnswered();
  if (noAnswered && noAnswered.length > 0) {
    confirmTitle.value = "您还有" + noAnswered.length + "题未作答，确定要交卷吗？";
    showConfirm();
  } else {
    submit();
  }
}

//提交
function submit() {
  let params = {
    userExamId: userExamId,
    examAnswers: questionAnswers.value
  };
  apiSubmitExam(params).then(() => {
    setTimeout(function() {
      //关闭当前窗口
      window.close();
      //打开考试结果详情页
      let url = router.resolve({
        path: `/exam/userExamResult/examDetail/` + userExamId
      });
      window.open(url.href, "_blank");
    }, 1000);
  });
}

//点击关闭按钮
function closeExam() {
  Modal.confirm({
    title: "提示",
    icon: createVNode(ExclamationCircleOutlined),
    content: "确定要退出考试吗？",
    onOk() {
      exitExam();
    },
    onCancel() {
    }
  });
}

//退出考试
function exitExam() {
  cacheAnswer();
}

//定时器时间到执行
function doHandler() {
  console.log("定时器时间到执行");
  submit();
}

//计算答题进度
const process = ref<number>();
watch(
  () => questionAnswers.value,
  () => {
    calcProcess();
  },
  { deep: true }
);

function calcProcess() {
  let answerIndex: any = [];
  questionAnswers.value.forEach((item: any) => {
    let index: any;
    if (item.index.toString().indexOf(".") != -1) {
      index = item.index.split(".")[0];
    } else {
      index = item.index;
    }
    if (!answerIndex.includes(index)) {
      answerIndex.push(index);
    }
  });
  process.value = Number((answerIndex.length * 100 / form.value.userExamQuestionList.length).toFixed(0));
}

function handleBeforeUnload(event) {
  //console.log("handleBeforeUnload")
  if (leaveStore.getLeaveTimes > 0) {
    sessionStorage.setItem("leave-times", leaveStore.getLeaveTimes);
  }
  //缓存考试答案
  cacheAnswer();
}

//页面销毁前解除监听
onBeforeUnmount(() => {
  window.removeEventListener("beforeunload", e => handleBeforeUnload(e));
});

//*****************切屏监听**********************//
let isCut = false;
let lastTime;

//切换选项卡，最小化窗口监听
document.addEventListener("visibilitychange", () => {
  let state = document.visibilityState;
  if (state == "hidden") {
    recordTime();
    //document.title = "我知道，你切换标签页了--tab1"
  } else {
    showTimeDiff();
    //document.title = "嘻嘻，你又回来了"
  }
});


//分屏监听
// 创建一个函数来检测屏幕是否被分屏显示
function checkScreenSplit() {
  // 获取屏幕的宽度
  const screenWidth = window.screen.width;

  // 获取当前窗口的宽度
  const windowWidth = window.innerWidth;

  // 计算屏幕实际显示的宽度和当前窗口宽度之间的差值
  const widthDifference = screenWidth - windowWidth;

  // 如果差值大于一定阈值，认为屏幕被分屏显示
  if (widthDifference > 100) { // 这里的阈值可以根据实际情况进行调整
    //document.title = '屏幕被分屏显示';
    if (!isCut) {
      recordTime();
    }
  } else {
    //document.title = '屏幕未被分屏显示';
    showTimeDiff();
  }
}

// 监听窗口大小变化，实时检测屏幕是否被分屏显示
window.addEventListener("resize", checkScreenSplit);


//记录切屏出去的时间
function recordTime() {
  isCut = true;
  lastTime = Date.now();
}

//计算切屏出去与切屏回来的时间差
function showTimeDiff() {
  if (!leaveOn.value) {
    return;
  }
  if (isCut) {
    let timeDiff = (Date.now() - lastTime) / 1000;
    //console.log(timeDiff);
    //如果时间差大于配置参数则切屏次数加1
    if (timeDiff > leaveTime.value) {
      countTimes();
    }
    isCut = false;
  }
}

//已经切换次数
const switchTimes = ref();
//可切换次数
const remaTimes = ref();

//计算切屏的次数
function countTimes() {
  let times = leaveStore.getLeaveTimes;
  //console.log(times)
  if (times == null) {
    leaveStore.setLeaveTimes(1);
    calcRemaTimes(1);
  } else {
    times++;
    leaveStore.setLeaveTimes(times);
    calcRemaTimes(times);
    if (remaTimes.value < 0) {//没有切屏次数了，则提交试卷
      submit();
      return;
    }
  }
  switchMsg.value = "您已切屏<span style='color:red;font-weight: 700'>" + switchTimes.value
    + "</span>次，还可切换<span style='color:red;font-weight: 700'>" + remaTimes.value
    + "</span>次，超过<span style='color:red;font-weight: 700'>" + totalLeaveTimes.value
    + "</span>次将<span style='color:red;font-weight: 700'>强行交卷</span>";
  handleConfirm("warning", switchMsg.value);
}

//计算剩余切屏次数
function calcRemaTimes(leaveTimes) {
  switchTimes.value = leaveTimes;
  remaTimes.value = totalLeaveTimes.value - switchTimes.value;
}

//切屏提示框
function handleConfirm(type, content) {
  createConfirm({
    iconType: type,
    title: "提示",
    content: content,
    okText: "我知道了",
    // 隐藏掉取消按钮
    cancelButtonProps: { style: { display: "none" } }
  });
}
</script>

<style scoped>
.all-box {
  padding: 10px 10px;
  display: flex;
  flex-direction: row;
}

.all-box-left {
  flex: 0 0 20%;
}

.left-box-normal {
}

.left-box {
  height: calc(100vh - 115px);
  position: fixed;
  overflow: auto;
  clear: both;
}

.a-card.is-always-shadow {
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
}

.a-card {
  border-radius: 4px;
  border: 1px solid #e6ebf5;
  background-color: #FFFFFF;
  color: #303133;
  transition: 0.3s;
}

.ant-card-bordered {
  border: none;
}

:deep(.ant-card-body) {
  padding: 20px;
}

.group-card {
  margin-bottom: 10px;
  line-height: 28px;
  width: 100%;
}

.typeClass {
  font-size: 14px;
  font-weight: 700;
  color: #448efc;
}

.group-card-body {
  line-height: 22px;
  font-size: 14px;
}

.numberClass {
  color: #448efc;
  font-style: italic;
}

.card-box {
  display: flex;
  flex-wrap: wrap;
  align-content: flex-start;
  margin-left: -5px;
  margin-top: 10px;
}

.card-box .item {
  width: 30px;
  height: 35px;
  background: #eee;
  border-radius: 2px;
  font-size: 12px;
  -webkit-box-align: center;
  align-items: center;
  cursor: pointer;
  margin: 5px 5px 10px 5px;
}

.card-box .item .num {
  text-align: center;
  padding: 3px;
  height: 20px;
  line-height: 14px !important;
}

.card-box .item .info {
  border-radius: 2px;
  background: #1890ff;
  color: #fff !important;
}

.card-box .item .warning {
  border-radius: 2px;
  background: #f1c40f;
  color: #fff !important;
}

.card-box .item .success {
  border-radius: 2px;
  background: #00bb00;
  color: #fff !important;
}

.ant-divider-horizontal {
  margin: 5px 0;
  width: 100%;
}

.ant-divider {
  background-color: #DCDFE6;
  position: relative;
}

.all-box-center {
  flex-grow: 1;
  margin-left: 20px;
  margin-right: 20px;
}

.content-card {
  margin-bottom: 20px;
  line-height: 28px;
}

.a-card.is-always-shadow {
  -webkit-box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
}

.list-box {
  display: flex;
  padding-bottom: 20px;
  border-bottom: #eee 3px dotted;
  margin-bottom: 20px;
}

.qu-box {
  margin-top: 30px;
  margin-bottom: 20px;
}

.qu-item {
  display: flex;
  margin-bottom: 20px;
}

.qu-item > .num {
  display: inline-block;
  background: url("../../assets/img/pick.png") no-repeat 100% 100%;
  background-size: contain;
  height: 35px;
  width: 35px;
  line-height: 30px;
  color: #fff;
  font-size: 14px;
  text-align: center;
  margin-right: 15px;
  flex-shrink: 0;
}

.qu-item > .content {
  flex-grow: 1;
  align-items: flex-start;
}

.qu-answer > .item {
  display: flex;
  border: #eee 1px solid;
  border-radius: 5px;
  line-height: 20px;
  margin: 15px 0 15px 0;
  padding: 10px;
  cursor: pointer;
  font-size: 14px;
}

.qu-answer > .item > .tag {
  width: 10px;
  font-weight: 700;
  color: #0a84ff;
  display: flex;
  align-items: center;
}

.qu-answer > .item > .content {
  flex-grow: 1;
  padding-left: 10px;
}

.all-box-right {
  flex: 0 0 20%;
  text-align: center;
  line-height: 32px;
  font-size: 14px;
}

.qu-answer > .active {
  background-color: rgba(0, 204, 85, 0.5);
}

.ant-divider-horizontal {
  margin: 0 0;
}

.tip {
  width: 30px;
  height: 20px;
  border-radius: 2px;
  font-size: 12px;
  align-items: center;
  cursor: pointer;
  margin: 5px 5px 10px 5px;
}

.tip .info {
  border-radius: 2px;
  background: #1890ff;
  color: #fff !important;
  text-align: center;
  padding: 3px;
  height: 20px;
  line-height: 14px !important;
}

.tip .warning {
  border-radius: 2px;
  background: #f1c40f;
  color: #fff !important;
  text-align: center;
  padding: 3px;
  height: 20px;
  line-height: 14px !important;
}

.tip .success {
  border-radius: 2px;
  background: #00bb00;
  color: #fff !important;
  text-align: center;
  padding: 3px;
  height: 20px;
  line-height: 14px !important;
}

:deep(span.xe-blanknumber) {
  width: 4em;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  margin: 0 2px;
  border-bottom: black solid 1px;
}

.answerCard {
  margin-bottom: 15px;
  display: flex;
  justify-content: center;
  align-items: center
}

.scoreStyle {
  margin-left: 5px;
  color: #0a8fe9;
}

.flex {
  display: flex;
}

.combinaClass {
  font-weight: 700;
  color: red;
  margin-left: 20px
}

.examTitle {
  font-weight: 500;
  color: #FFF;
  font-size: 16px;
}

.countDownClass {
  height: 30px;
  width: 125px;
  padding: 2px 1px;
  border-radius: 10px;
  margin-top: 5px;
}

.countdown-item {
  padding: 3px 6px;
  border-radius: 3px;
  color: #fff;
  font-size: 16px;
  background-color: #c00;
}

.timeColon {
  color: #FFF;
  font-weight: 500;
  font-size: 16px;
  margin: 0 5px;
}

.processClass {
  text-align: center;
  margin: 40px 0;
}

.examInfo {
  margin-top: 10px;
  color: white;
}

.float-notice{
	position:absolute;
	top:45%;
	left:-200px;
	width:200px;
	line-height:32px;
	background-color:#ffffff;
	border:1px solid #efefef;
	border-radius:5px;
	text-align:center;
	p{
		margin:0;
	}
	&.active{
		left:100%;
		transition: all 10s linear;
	}
}
</style>
